package juc.threadactiveness;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;


public class PhilosopherEatTest {

    public static void main(String[] args) {
        //初始化五根筷子
        Chopstick c1 = new Chopstick(1);
        Chopstick c2 = new Chopstick(2);
        Chopstick c3 = new Chopstick(3);
        Chopstick c4 = new Chopstick(4);
        Chopstick c5 = new Chopstick(5);

        //思考：如何打破循环死锁 ---把阿基米德的顺序调整下
        new Philosoher("苏格拉底",c1,c2).start();
        new Philosoher("柏拉图",c2,c3).start();
        new Philosoher("亚里士多德",c3,c4).start();
        new Philosoher("赫拉克利德",c4,c5).start();
        new Philosoher("阿基米德",c5,c1).start();
    }

}

/**
 * 筷子对象
 */
@Data
@AllArgsConstructor
class Chopstick{
    int number;

    public String toString(){
        return "筷子{"+number+"}";
    }
}

@Slf4j
class Philosoher extends Thread{
    private Chopstick left;
    private Chopstick right;
    public Philosoher(String name,Chopstick left,Chopstick right){
        super(name);
        this.left=left;
        this.right=right;
    }
    public void eat(){
        log.debug("eating.......");
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void think(){
        log.debug("thinking.......");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while (true){
            //获得左手筷子
            synchronized (left){
                log.debug("获得左手筷子"+left.getNumber());
                //获得右手筷子
                synchronized (right){
                    log.debug("获得右手手筷子"+left.getNumber());
                    eat();
                }
                //放下右手筷子
            }
            //放下左手筷子
            log.debug("吃完了，把筷子放回了原处,开始thinking");
            think();
        }
    }
}